package com.rover.system.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.UserQuery;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.common.Common;
import com.grid.DataGrid;
import com.grid.Page;
import com.rover.system.dao.BaseDao;
import com.rover.system.entity.Role;
import com.rover.system.entity.User;
import com.utils.Encrypt;

@Service("userService")
@Transactional
public class UserService{
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private BaseDao dao;
	
	@Autowired
	private 	IdentityService	identityService;

	@Transactional
	public User getUserByUserName(String userName){
		if(StringUtils.isNotBlank(userName)){
			List<User> users = dao.findHql("from User u where u.loginName='" + userName + "'",null);
			if(null != users && users.size() != 0){
				return users.get(0);
			}
		}
		return null;
	}
	
	@Transactional(readOnly = true)
    public DataGrid query(Page page,Map<String, Object> params, String hql){
        DataGrid dataGrid=new DataGrid();
		hql = "from User " + hql;
		String rolesName = "",rolesId = "";
		List<User> users = dao.findPageHql(hql, params,page.getPageNo() , page.getPageSize());
		if(null != users && users.size() != 0){
			for(User user : users){
				rolesName = "";
				rolesId = "";
//				List<UserRole> userRoles = dao
//						.findHql("from UserRole u where u.tuser='" + user.getId()
//								+ "'",null);
//				for (UserRole ur : userRoles) {
//					rolesName += ur.getTrole().getName() + ",";
//					rolesId += ur.getTrole().getId() + ",";
//				}
				//删除最后一个,
				if (rolesName.length() > 0) {
					rolesName = rolesName.substring(0, rolesName.length() - 1);
					rolesId = rolesId.substring(0, rolesId.length() - 1);
				}
				
			}
		}
        dataGrid.setResult(users);
		String totalHql = "select count(*) " + hql;
        dataGrid.setTotalCount(dao.countHql(totalHql, params));
	    return dataGrid;
	}
	
	@Transactional(readOnly = true)
	public Boolean isAddNameRepeat(String name){
		List<User> users = dao.findHql("from User u where u.loginName='" + name + "'",null);
		if(users.size() > 0){
			return Boolean.FALSE;
		}else {
			return Boolean.TRUE;
		}
	}
	
	@Transactional(readOnly = true)
	public Boolean isEditNameRepeat(String name,Integer id){
		 Map<String, Object> params = new HashMap<String, Object>();
		 params.put("name", name);
 		params.put("id", id);
		List<User> users = dao.findHql("from User where loginName=:name and id<>:id",params);
		if(users.size() > 0){
			return Boolean.FALSE;
		}else {
			return Boolean.TRUE;
		}
	}
	
	/*
	 * 获取此用户的角色id
	 * @user  用户实体类
	 * */
	@SuppressWarnings("unchecked")
	@Transactional
	public List<String> getUserRole(User user){
//	Query q=	userRoleDao.getCurrentSession().createQuery("select ur.trole.id from UserRole ur where ur.tuser=:user");
//		q.setEntity("user", user);
//		  return q.list();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("user", user);
	return	dao.findHql("select ur.trole.id from UserRole ur where ur.tuser=:user", params);
	
	}
	/*
	 * 获取此用户是否是管理员
	 * @user  用户实体类
	 * */
	@SuppressWarnings("unchecked")
	@Transactional
	public Boolean getIsAdmin(Integer userId){
//	Query q=	userRoleDao.getCurrentSession().createQuery("from Role where  id in (select ur.trole.id from UserRole ur where ur.tuser=:user)");
//		q.setEntity("user", user);
//		List<Role> li=q.list();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", userId);
		List<String> li=dao.<String>findSQL("select ur.ROLE_ID from S_UserRole ur where ur.USER_ID=:userId", params);

		Boolean isAdmin=false;
		for(String i :li){
			if(i.equals("000")){
				isAdmin=true;
		        break;
			}
		}
	  return isAdmin;
	}
	
	
	/**
     * 添加工作流用户以及角色
     * @param user      用户对象{@link User}
     * @param roleIds   用户拥有的角色ID集合
     */
    private void newActivitiUser(User user, List<Role> roleIds) {
        String userId = user.getId().toString();
 
        // 添加用户
        saveActivitiUser(user);
 
        // 添加membership
        addMembershipToIdentify(roleIds, userId);
    }
 
    /**
     * 添加一个用户到Activiti {@link org.activiti.engine.identity.User}
     * @param user  用户对象, {@link User}
     */
    private void saveActivitiUser(User user) {
        String userId = user.getId().toString();
        org.activiti.engine.identity.User activitiUser = identityService.newUser(userId);
        cloneAndSaveActivitiUser(user, activitiUser);
        logger.debug("add activiti user: {}", ToStringBuilder.reflectionToString(activitiUser));
    }
 
    /**
     * 添加Activiti Identify的用户于组关系
     * @param roleIds   角色ID集合
     * @param userId    用户ID
     */
    private void addMembershipToIdentify(List<Role> roleIds, String userId) {
        for (Role role : roleIds) {
           // Role role = roleManager.getEntity(roleId);
            logger.debug("add role to activit: {}", role);
            identityService.createMembership(userId, role.getId().toString());
        }
    }
 
    /**
     * 更新工作流用户以及角色
     * @param user          用户对象{@link User}
     * @param roleIds       用户拥有的角色ID集合
     * @param activitiUser  Activiti引擎的用户对象，{@link org.activiti.engine.identity.User}
     */
    private void updateActivitiData(User user, List<Role> roleIds, org.activiti.engine.identity.User activitiUser) {
 
        String userId = user.getId().toString();
 
        // 更新用户主体信息
        cloneAndSaveActivitiUser(user, activitiUser);
 
        // 删除用户的membership
        List<org.activiti.engine.identity.Group> activitiGroups = identityService.createGroupQuery().groupMember(userId).list();
        for (org.activiti.engine.identity.Group group : activitiGroups) {
            logger.debug("delete group from activit: {}", ToStringBuilder.reflectionToString(group));
            identityService.deleteMembership(userId, group.getId());
        }
 
        // 添加membership
        addMembershipToIdentify(roleIds, userId);
    }
 
    /**
     * 使用系统用户对象属性设置到Activiti User对象中
     * @param user          系统用户对象
     * @param activitiUser  Activiti User
     */
    private void cloneAndSaveActivitiUser(User user, org.activiti.engine.identity.User activitiUser) {
        activitiUser.setFirstName(user.getName());
        activitiUser.setLastName(StringUtils.EMPTY);
        activitiUser.setPassword(StringUtils.EMPTY);
        activitiUser.setEmail(user.getEmail());
        identityService.saveUser(activitiUser);
    }
	/*
	*保存数据
	*/
	@Transactional
	public void save(User user){
		//添加的时候初始化密码
		if(user.getId()==null){
			user.setPassword(Encrypt.md5(Common.ADMIN_PASSWORD));
		}
		else{
			//更新的时候删除对应的角色
			 Map<String, Object> params=new HashMap<String, Object>();
			 params.put("user", user);
            dao.executeHql("delete UserRole ur where ur.tuser=:user", params);
			//将更新的数据覆盖原用户数据
             params.clear();
   		     params.put("id", user.getId());
			 User u = dao.<User>findHql("from User where id=:id",params).get(0);
			 u.setName(user.getName());
			 u.setLoginName(user.getLoginName());
			 u.setEmail(user.getEmail());
			 u.setStatus(user.getStatus());
			 user = u;
		}
        dao.saveOrUpdate(user);
        List<Role> liRoles = new ArrayList<Role>();
		//保存角色
		String roleIds = user.getId().toString();
		if(StringUtils.isNotBlank(roleIds)){
			String[] strRole = roleIds.split(",");
			
//			UserRole ur = null;
//			for(String str :strRole){
//				List<Role> liRole=	dao.findHql("from Role where id='"+str+"'",null);
//				if(liRole.size()>0){
//					ur=new UserRole();
//					ur.setTrole(liRole.get(0));
//					ur.setTuser(user);
//                    dao.save(ur);
//                    liRoles.add(liRole.get(0));
//				}
//			}
		}
		 // 同步数据到Activiti Identify模块
            UserQuery userQuery = identityService.createUserQuery();
            List<org.activiti.engine.identity.User> activitiUsers = userQuery.userId(user.getId().toString()).list();
            if (activitiUsers.size() == 1) {
                updateActivitiData(user, liRoles, activitiUsers.get(0));
            } else if (activitiUsers.size() > 1) {
                String errorMsg = "发现重复用户：id=" + user.getId();
                logger.error(errorMsg);
                throw new RuntimeException(errorMsg);
            } else {
                newActivitiUser(user, liRoles);
            }
       
	}
	

	/*
	*保存用户启用/禁用数据
	*/
	@Transactional
	public void saveEnable(User user) {
        dao.saveOrUpdate(user);
	}
	
	/*
	*删除用户
	*/
	@Transactional
	public void delete(Integer id) {
        dao.delete(User.class,id);
        identityService.deleteUser(id.toString());
     
	}
	
	/*
	 * 初始化密码
	 * @id  要初始化的用户id
	 * */
	@Transactional
	public void initPassword(Integer id) {
		 Map<String, Object> params = new HashMap<String, Object>();
 		params.put("id", id);
		User user = dao.<User>findHql("from User where id=:id", params).get(0);
		user.setPassword(Encrypt.md5(Common.ADMIN_PASSWORD));
        dao.saveOrUpdate(user);
	}
	
	/*
	 * 根据HQL查找对应user表中数据
	 * */
	@Transactional
	public List<User> findByHql(String hql) {
		return dao.findHql(hql,null);
	}
	

	/*
	 * 修改密码
	 * */
	@Transactional
	public Map<String, Object> savePassword(Integer id,String password,String newPwd,String newPwdTwo){
		Map<String, Object> map = new HashMap<String, Object>();
		String message = null;
		Boolean flag = Boolean.TRUE;
		 Map<String, Object> params = new HashMap<String, Object>();
	 		params.put("id", id);
		List<User> users = dao.findHql("from User where id=:id",params);
		User user = users.get(0);
		if(!newPwd.equals(newPwdTwo)){
			message = "两次输入密码不符，请重新输入";
			flag = Boolean.FALSE;
		}else if(StringUtils.isNotBlank(password)){
			if(!Encrypt.md5(password).equals(user.getPassword())){
				message = "原密码输入错误，请重新输入";
				flag = Boolean.FALSE;
			}else {
				message = "密码修改成功";
				flag = Boolean.TRUE;
				user.setPassword(Encrypt.md5(newPwd));
                dao.save(user);
			}
		}else {
			message = "原密码输入不能为空";
			flag = Boolean.FALSE;
		}
		map.put("success", flag);
		map.put("message", message);
		return map;
	}
	
	/*
	 * 根据Id寻找对应user
	 * */
	@Transactional
	public User getUserById(Integer id){
		 Map<String, Object> params = new HashMap<String, Object>();
	 		params.put("id", id);
		List<User> users = dao.findHql("from User where id=:id",params);
		if(null != users && users.size() != 0){
			return users.get(0);
		}
		return null;
	}
	
}
